#include "sky.h"
#include "math.h"
#include <string>
#include "../algebra/Matrix.h"
#include "../geom/GeomMatrix.h"
using namespace sceneelems;

Sky::Sky()
{}

Sky::~Sky()
{
	delete m_skyShader;
}

void Sky::setSkyBrightness(float value)
{
    m_skyShader->setUniform1f("skyBrightness",value);
}

void Sky::initialize()
{
	m_skyShader = new glutil::ShaderProgram();
	m_skyShader->attachShaderFromFile(GL_VERTEX_SHADER,"data/sky.vert");
	m_skyShader->attachShaderFromFile(GL_FRAGMENT_SHADER,"data/sky.frag");
	m_skyShader->link();
	m_skyShader->bind();

    m_skyShader->setUniform3f("sunVector",1,-0.4,1); // LA Y DEL SOL ESTA DADA LA VUELTA
    setSkyBrightness(500.0);
	m_skyShader->unbind();
}

void Sky::setSkyProperties(slotsdata::SkyProperties props)
{
	m_skyShader->setUniform3f("sunVector",props.sunVector().dx,props.sunVector().dy,props.sunVector().dz);
	m_skyShader->setUniform3f("topColor",props.topColor().dx,props.topColor().dy,props.topColor().dz);
	m_skyShader->setUniform3f("bottomColor",props.bottomColor().dx,props.bottomColor().dy,props.bottomColor().dz);
	m_skyShader->setUniform3f("hazeColor",props.hazeColor().dx,props.hazeColor().dy,props.hazeColor().dz);
	m_skyShader->setUniform1f("sunCoverAngle",props.sunCoverAngle());
	m_skyShader->setUniform1f("haloCoverAngle",props.haloCoverAngle());
	m_skyShader->setUniform1f("sunIntensityFactor",props.sunIntensityFactor());
	m_skyShader->setUniform1f("sunSmoothBorder",props.sunSmoothBorder());
	m_skyShader->setUniform1f("hazeStrength",props.hazeStrength());
	m_skyShader->setUniform1f("hazeAmmount",props.hazeAmmount());
	m_skyShader->setUniform1f("skyBrightness",props.skyBrightness());
}

// All parameters must be in radians!
void Sky::draw(const geom::Vector3D & camViewVector, float cameraVerticalFOV, float cameraHorizontalFOV)
{
/*
	algebra::Vector4f maxVector, minVector;
	algebra::Vector4f camVec;
	for(int i=0;i<3;++i)
		camVec[i] = camViewVector.dv[i];
	camVec[3] = 0;

	algebra::Matrix4f rotMatrix = geom::createRotationMatrixAroundY(-cameraHorizontalFOV/2);
	maxVector = rotMatrix * camVec;

//	float upAngle = acos(maxVector[1]);
    //float rotAngle = atan2(maxVector[0], maxVector[2]);
*/
    float upAngle = -acos(camViewVector.dy);
    float rotAngle = -atan2(camViewVector.dx, camViewVector.dz);

    m_skyShader->setUniform2f("viewAngle",rotAngle, upAngle-M_PI/2);
    m_skyShader->setUniform2f("halffov", cameraHorizontalFOV/2, cameraVerticalFOV/2);

	m_skyShader->bind();

	glBegin(GL_QUADS);
	{
		glColor3f(0.81f,0.9f,1.0f);
		glMultiTexCoord2f(0,-1,-1);
		glVertex3f(-1.0,-1.0,-1.0);

		glMultiTexCoord2f(0,1,-1);
		glVertex3f( 1.0,-1.0,-1.0);

		glMultiTexCoord2f(0,1,1);
		glVertex3f( 1.0, 1.0,-1.0);

		glMultiTexCoord2f(0,-1,1);
		glVertex3f(-1.0, 1.0,-1.0);
	}
	glEnd();

	m_skyShader->unbind();
}




